package com.example.tongyao.utils;

import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * dnstools >>> 【】
 * ftp工具类
 *
 * @author: tongyao
 * @since: 2022-07-05 14:19
 */
public class FtpUtils {

    public static FTPClient connection(String ip,int port,String user,String password) throws Exception{
        FTPClient ftpClient = new FTPClient();

        ftpClient.connect(ip, port);
        ftpClient.login(user, password);

        // 二进制类型传输
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

        // 主动
        ftpClient.enterLocalActiveMode();
        System.out.println("ftp："+ip+"，连接成功！");
        return ftpClient;
    }

    public static boolean uploadFile(FTPClient ftpClient,String fileName,InputStream inputStream,String targetPath) throws Exception{
        // 二进制类型传输
        //fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");
        //fileName = new String(fileName.getBytes("iso-8859-1"),"GBK");

        // 进入目录
        ftpClient.changeWorkingDirectory(targetPath);
        return ftpClient.storeFile(fileName, inputStream);
    }

    public static boolean deleteFile(FTPClient ftpClient,String fileName,String targetPath) throws Exception{

        // 进入目录
        ftpClient.changeWorkingDirectory(targetPath);
        return ftpClient.deleteFile(fileName);
    }


    public static boolean reName(FTPClient ftpClient,String oldName,String newName) throws Exception{
        return ftpClient.rename(oldName,newName);
    }

    public static void disconnect(FTPClient ftpClient){
        try {
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        FTPClient ftp = new FTPClient();
        ftp.connect("127.0.0.1", 21);
        ftp.login("tongyao", "tongyao");

        // 设置文件类型（不设置可能导图片乱码）
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

        InputStream is  = new FileInputStream("D:\\test.csv");
        // 存储在服务端的名称
        ftp.storeFile("测试.csv", is);
        ftp.logout();

        System.out.println("上传成功");
    }
}
